package com.bckj.freshnow.order.trade.fsm;

import com.alibaba.cola.statemachine.builder.StateMachineBuilder;
import com.alibaba.cola.statemachine.builder.StateMachineBuilderFactory;
import com.bckj.freshnow.order.fsm.IOrderStateMachine;
import com.bckj.freshnow.order.fsm.enums.OrderStateMachineIdEnum;
import com.bckj.freshnow.order.trade.fsm.enums.TradeOrderEventEnum;
import com.bckj.freshnow.order.trade.fsm.enums.TradeOrderStatusEnum;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;


@Component
@RequiredArgsConstructor
public class TradeOrderStateMachine implements IOrderStateMachine {

//    private final TradeOrderCondition tradeOrderCondition;
    private final TradeOrderAction tradeOrderAction;

    @Override
    public OrderStateMachineIdEnum getStateMachineIdEnum() {
        return OrderStateMachineIdEnum.TRADE_ORDER;
    }

    @PostConstruct
    public void initialize() {
        //初始化状态机
        StateMachineBuilder<TradeOrderStatusEnum, TradeOrderEventEnum, TradeOrderContext> builder
                = StateMachineBuilderFactory.create();
        //账单支付完成
        builder.externalTransition().from(TradeOrderStatusEnum.PAY_ONLINE).to(TradeOrderStatusEnum.WAITING_USE)
                .on(TradeOrderEventEnum.PAY_SUCCESS)
                .perform(tradeOrderAction);
        //用户发起取消订单或订单超时取消
        builder.externalTransition().from(TradeOrderStatusEnum.PAY_ONLINE).to(TradeOrderStatusEnum.CANCEL)
                .on(TradeOrderEventEnum.CANCEL_ORDER)
                .perform(tradeOrderAction);
        //订单超过售后期
        builder.externalTransition().from(TradeOrderStatusEnum.WAITING_USE).to(TradeOrderStatusEnum.FINISHED)
                .on(TradeOrderEventEnum.OVER_AFTER_SALE)
                .perform(tradeOrderAction);
        //订单全部退款
        builder.externalTransition().from(TradeOrderStatusEnum.WAITING_USE).to(TradeOrderStatusEnum.TRADE_CLOSE)
                .on(TradeOrderEventEnum.FULL_REFUND)
                .perform(tradeOrderAction);
        //订单存在进行中的售后单
        builder.externalTransition().from(TradeOrderStatusEnum.WAITING_USE).to(TradeOrderStatusEnum.AFTER_SALE)
                .on(TradeOrderEventEnum.HAVE_AFTER_SALE)
                .perform(tradeOrderAction);
        //售后单处理完成
        builder.externalTransition().from(TradeOrderStatusEnum.AFTER_SALE).to(TradeOrderStatusEnum.FINISHED)
                .on(TradeOrderEventEnum.AFTER_SALE_SUCCESS)
                .perform(tradeOrderAction);
        builder.build(getStateMachineIdEnum().getMachineId());
    }
}
